#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"
#include "ad_spi.h"
#include "event.h"
#include "stdio.h"


int g_adc_value[ADC_CN] = {0};
int g_adc_index = 0;


void spi_init(void)  
{    
    GPIO_InitTypeDef GPIO_InitStructure;    
    
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_4
                                  | GPIO_Pin_5 | GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;                                                  
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;     
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_Init(GPIOA,&GPIO_InitStructure);

    SPI_CS_A_HIGH;
    SPI_CS_B_HIGH;
    SPI_CS_C_HIGH;
    SPI_CS_D_HIGH;

    SPI_CLK_LOW;
}


uint8_t is_channel_b_rdy(void)
{
    SPI_CS_B_LOW;
    
    return SPI_DO;
}

int32_t read_channel_b(void)    
{    
    int32_t adc_data = 0;
    uint8_t  i;

    SPI_CS_B_LOW;

    for (i = 0; i < 24; i++) {
        adc_data <<= 1;
        SPI_CLK_HIGH;

        if (SPI_DO & 0x01){
            adc_data |= 1;
        }
        SPI_CLK_LOW;
    }

    SPI_CS_B_HIGH;

    return adc_data;
}   

void get_adc_value(void)
{
    if(g_adc_index < ADC_CN){
        if(is_channel_b_rdy() == 0){
            g_adc_value[g_adc_index] = read_channel_b() & 0x000FFFFF;
            g_adc_index++;
        }
    }

    if(g_adc_index == ADC_CN){
        g_adc_index = 0;
        event_set(kEventADCDone);
    }
}

float avg_ph_adc_value()
{
    int i;
    int min, max, sum = 0;
    float ret;
    
    min = g_adc_value[0];
    max = g_adc_value[0];
    sum = g_adc_value[0];
        
    for(i = 1; i < ADC_CN; i++) {
        if(g_adc_value[i] < min)
            min = g_adc_value[i];

        if(g_adc_value[i] > max)
            max = g_adc_value[i];

        sum += g_adc_value[i];
    }

    ret = (sum - max - min) * 1.0 / (ADC_CN - 2);
    ret = ret * 2.508 / 1048576;

    return ret;

}


void print_adc_value(void)
{
    float voltage;

    voltage = avg_ph_adc_value();
    printf("%-.3f\n", voltage);

}

void adc_event_handler_init(void)
{
    event_set_handler(kEventADCDone, print_adc_value);
}



